package eastmoney

import (
	"net/http"
)

func (this *StockService) getHttpClient() *http.Client {
	if this.Client != nil {
		return this.Client
	}
	return http.DefaultClient
}

func (this *StockService) getWithRetry(url string, needToken bool) (resp *http.Response, err error) {
	currentToken := this.tokenKeeper.Get()
	if needToken && currentToken != "" {
		url = url + "&token=" + currentToken
	}
	log.Println(url)
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return
	}
	client := this.getHttpClient()
	resp, err = client.Do(req)
	if resp.StatusCode == http.StatusNotFound {
		_, newToken := this.tokenKeeper.ComputeWhen(
			func(currentValue string) bool {
				return currentValue == currentToken
			},
			func(oldValue string) string {
				return this.requestToken()
			},
		)
		if currentToken != newToken && newToken != "" {
			return this.getWithRetry(url, needToken)
		} else {
			log.Panicln("refresh token failed")
		}
	}
	return
}
